package cshi.network;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TestMyServer {
	//use telnet to act as client for testing
	public static void main(String[] args)
	{
		//srv_test();
		try {
			int i = 1;
			ServerSocket ss = new ServerSocket(8000);
			System.out.println("create socket at 8000...");
			
			while (true) {
				Socket incoming = ss.accept();
				System.out.println("spawing " + i);
				Runnable runnable = new ThreadEchoServer(incoming);
				Thread t = new Thread(runnable);
				t.start();
				i++;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public void func()
	{
		try {
			String host = "www.baidu.com";
			InetAddress[] addr = InetAddress.getAllByName(host);
			for (InetAddress ia:addr)
				System.out.println(ia);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public static void srv_test()
	{
		try {
			ServerSocket ss = new ServerSocket(8000);
			System.out.println("create socket at 8000...");
			
			Socket incoming = ss.accept();
			try {
				InputStream ist = incoming.getInputStream();
				OutputStream ost = incoming.getOutputStream();
				
				Scanner in = new Scanner(ist);
				PrintWriter out = new PrintWriter(ost,true);
				
				out.println("hello. Enter bye to exit");
				
				//read client resp
				boolean done = false;
				while (!done && in.hasNext()) {
					String line = in.nextLine();
					out.println("Echo:" + line);
					if (line.trim().equals("BYE"))
						done = true;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			finally {
				incoming.close();
				System.out.println("client closed");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
}

class ThreadEchoServer implements Runnable
{
	public ThreadEchoServer(Socket s) {
		incoming = s;
	}
	
	public void run() {
		try {
			InputStream is = incoming.getInputStream();
			OutputStream os = incoming.getOutputStream();
			Scanner in = new Scanner(is);
			
			//true is very important !!. If no ,then flush should be called
			PrintWriter out = new PrintWriter(os,true);
			
			out.println("hello. Enter Bye to exit");
			//read client resp
			boolean done = false;
			while (!done && in.hasNext()) {
				String line = in.nextLine();
				out.println("Echo:" + line);
				if (line.trim().equals("Bye"))
					done = true;
			}
				
		} catch(Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			// TODO: handle finally clause
			//incoming.close();
			System.out.println("client closed");
		}
	}
	private Socket incoming;
}
